/*
 * log.cpp
 *
 *  Created on: 2012-6-8
 *      Author: liujian
 */

#include"log.h"
/*LOG_LEVEL为什么不能加到log.h里面去*/
using namespace std;

void do_log(const char*file_name, LOG_LEVEL lev, const char* fmt,...)
{
	char time_buf[200];
	char vsnprintf_buf[300];
	int n;
	va_list ap;
	time_t t;
	struct tm *tm_p = NULL;
	string log_str;
	FILE* fp = NULL;

	t = time(NULL);
	tm_p = localtime(&t);

	if (NULL == tm_p){
		fprintf(stderr,"do_log localtime return NULL\n");
		return;
	}

	if ((n = strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S--", tm_p)) == 0) {
	   fprintf(stderr, "do_log strftime return 0\n");
	   return;
	}

	switch(lev){

		case LOG_EMERG:
			log_str = "[EMERG]--";
			break;

		case LOG_ALERT:
			log_str = "[ALERT]--";
			break;

		case LOG_CRIT:
			log_str = "[CRIT]--";
			break;

		case LOG_ERR:
			log_str = "[ERR]--";
			break;

		case LOG_WARNING:
			log_str = "[WARNING]--";
			break;

		case LOG_NOTICE:
			log_str = "[NOTICE]--";
			break;

		case LOG_INFO:
			log_str = "[INFO]--";
			break;

		case LOG_DEBUG:
			log_str = "[DEBUG]--";
			break;

		default:
			log_str = "[UNKNOWN]--";
			break;
	}

	log_str += time_buf;
	va_start(ap,fmt);

	/*其实可以使用vsnprintf*/
	vsnprintf(vsnprintf_buf,sizeof(vsnprintf_buf),fmt,ap);
#if 0
	int d;
	char *s = NULL;
	char int_buf[30];/*超过int长度就可以了*/

	while(*fmt){
		switch(*fmt){
			case 's':
				s = va_arg(ap, char *);
				log_str += s;
				fmt++;
				break;

			case 'd':
				d = va_arg(ap, int);
				memset((void*)int_buf, 0, sizeof(int_buf));
				snprintf(int_buf, sizeof(int_buf),"%d", d);
				log_str += int_buf;
				fmt++;
				break;
			default:
				fmt++;
				break;
		}
	}
	va_end(ap);
#endif

	log_str += vsnprintf_buf;
	log_str += '\n';

	if ( (fp = fopen(file_name,"a+")) == NULL){
		fprintf(stderr,"fopen log file:%s error\n",file_name);
		return;
	}
	fputs(log_str.c_str(), fp);
	fclose(fp);
	return;
}
